package com.yc.jpyy.mobile.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.UUID;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import org.apache.tomcat.util.http.fileupload.FileItem;
import org.apache.tomcat.util.http.fileupload.RequestContext;
import org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory;
import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload;
import org.apache.tomcat.util.http.fileupload.servlet.ServletRequestContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.yc.jpyy.base.bean.RestResponse;
import com.yc.jpyy.base.config.Config;
import com.yc.jpyy.base.controller.BaseController;
import com.yc.jpyy.mobile.dao.BizDao;
import com.yc.jpyy.mobile.service.BizService;

@Controller
@RequestMapping(value = "/uploadinfo")
public class UploadController extends BaseController {

	@Autowired
	private BizService bizService;
	private static Logger logger = LoggerFactory
			.getLogger(UploadController.class);
	@Autowired
	private BizDao bizDao;

	/**
	 * 图片上传、保存
	 * 
	 * @param request
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@SuppressWarnings("finally")
	@RequestMapping(value = "/uploadpicinfo", method = { RequestMethod.GET,
			RequestMethod.POST }, produces = "application/json; charset=utf-8")
	public @ResponseBody String uploadpicinfo(HttpServletRequest request)
			throws UnsupportedEncodingException {

		RestResponse response = new RestResponse();
		try {
			String userid = request.getParameter("userid");
			String videoId = request.getParameter("videoId");
			String imgdata = request.getParameter("imgdata");
			if (userid != null && !userid.isEmpty() && videoId != null
					&& !videoId.isEmpty()) {
				// 保存图片到文件夹
				Map<String, Object> path = new HashMap<String, Object>();
				if(imgdata != null && !imgdata.isEmpty())
				{
					path= updatePersonPhoto(imgdata);
				}
				else
				{
					path= uploadpic(request);
				}
				if (path != null) {
					// 添加图片到数据库
					Map<String, Object> map = new HashMap<String, Object>();
					map.put("userid", userid);
					map.put("image", path.get("uploadurl").toString());
					map.put("videoid", videoId == null ? "" : videoId);
				 
					int result = bizDao.Insertcheckpic(map);

					if (result > 0) {
						response.setReturnMsg(0, "操作成功");
					}
				} else {
					response.setReturnMsg(1, "上传图片失败...");
					return response.toJSON();
				}

			} else {
				response.setReturnMsg(1, "用户ID、视频ID不能为空...");
				return response.toJSON();
			}

		} catch (Exception e) {

			logger.info("上传异常" + e.toString());
			// 异常信息
			response.setErrorcode(1);
			response.setMessage("获取失败！");

		} finally {
			return response.toJSON();
		}
	}
	
	/**
	 * 学习照片上传、保存
	 * 
	 * @param request
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@SuppressWarnings("finally")
	@RequestMapping(value = "/addStudyPhoto", method = { RequestMethod.GET,
			RequestMethod.POST }, produces = "application/json; charset=utf-8")
	public @ResponseBody String addStudyPhoto(HttpServletRequest request)
			throws UnsupportedEncodingException {
		RestResponse response = new RestResponse();
		try {
			//拍照时间
			String photoTime = request.getParameter("photoTime");
			//课堂ID
			String classId = request.getParameter("classId");
			//学员全国编号
			String stuNum = request.getParameter("stuNum");
			//类型
			String eventType = request.getParameter("eventType");
			//照片64进制数据
			String image64Base = request.getParameter("image64Base");
			if (photoTime != null && !photoTime.isEmpty() && classId != null
					&& !classId.isEmpty()&& stuNum != null&& !stuNum.isEmpty()&& eventType != null&& !eventType.isEmpty()) {
				// 保存图片到文件夹
				Map<String, Object> path = new HashMap<String, Object>();
				if(image64Base != null && !image64Base.isEmpty())
				{
					path= updatePersonPhoto(image64Base);
				}
				else
				{
					path= uploadpic(request);
				}
				if (path != null) {
					// 添加图片到数据库
					Map<String, Object> map = new HashMap<String, Object>();
					map.put("photoTime", photoTime);
					map.put("classId", classId);
					map.put("stuNum", stuNum);
					map.put("eventType", Integer.parseInt(eventType));
					map.put("image", path.get("uploadurl").toString());
					int result = bizDao.addStudyPhoto(map);

					if (result <=0) {
						response.setErrorcode(1);
						response.setMessage("操作失败！");
					}
				} else {
					response.setErrorcode(1);
					response.setMessage("上传图片失败！");
				}

			} else {
				response.setErrorcode(1);
				response.setMessage("缺少必填字段！");
			}

		} catch (Exception e) {
			logger.info("上传异常" + e.toString());
			// 异常信息
			response.setErrorcode(1);
			response.setMessage("操作异常！");

		} finally {
			return response.toJSON();
		}
	}
	
	/**
	 * 视频学习照片接口
	 * 
	 * @param request
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@SuppressWarnings("finally")
	@RequestMapping(value = "/addVideoPhoto", method = { RequestMethod.GET,
			RequestMethod.POST }, produces = "application/json; charset=utf-8")
	public @ResponseBody String addVideoPhoto(HttpServletRequest request)
			throws UnsupportedEncodingException {
		RestResponse response = new RestResponse();
		try {
			//主键ID
			String Id = request.getParameter("Id");
			//学员编号ID
			String studentId = request.getParameter("studentId");
			//拍照时间
			String photoTime = request.getParameter("photoTime");
			//视频ID
			String videoId = request.getParameter("videoId");
			//照片64进制数据
			String image64Base = request.getParameter("image64Base");
			if (Id != null && !Id.isEmpty() && studentId != null
					&& !studentId.isEmpty()&& photoTime != null&& !photoTime.isEmpty()&& videoId != null&& !videoId.isEmpty()) {
				// 保存图片到文件夹
				Map<String, Object> path = new HashMap<String, Object>();
				if(image64Base != null && !image64Base.isEmpty())
				{
					path = updatePersonPhoto(image64Base);
				}
				else
				{
					path = uploadpic(request);
				}
				if (path != null) {
					// 添加图片到数据库
					Map<String, Object> map = new HashMap<String, Object>();
					map.put("Id", Id);
					map.put("studentId", Integer.parseInt(studentId));
					map.put("photoTime", photoTime);
					map.put("videoId", videoId);
					map.put("image", path.get("uploadurl").toString());
					int result = bizDao.addVideoPhoto(map);
					if (result <= 0) {
						response.setErrorcode(1);
						response.setMessage("操作失败！");
					}
				} else {
					response.setErrorcode(1);
					response.setMessage("上传图片失败！");
				}

			} else {
				response.setErrorcode(1);
				response.setMessage("缺少必填字段！");
			}

		} catch (Exception e) {
			logger.info("上传异常" + e.toString());
			// 异常信息
			response.setErrorcode(1);
			response.setMessage("操作异常！");

		} finally {
			return response.toJSON();
		}
	}	
	
	@SuppressWarnings("finally")
	public Map<String, Object> updatePersonPhoto(String imgStr)
			throws UnsupportedEncodingException {

		RestResponse response = new RestResponse();
		try {
			Map<String, Object> map = new HashMap<String, Object>();
			Calendar date = Calendar.getInstance();
			String nfs = "";
			String path = "";

			SimpleDateFormat format1 = new SimpleDateFormat("yyyy ");
			SimpleDateFormat format2 = new SimpleDateFormat("M ");
			SimpleDateFormat format3 = new SimpleDateFormat("d ");
			SimpleDateFormat format4 = new SimpleDateFormat("H ");
			String year = format1.format(date.getTime()).trim();// 年
			String month = format2.format(date.getTime()).trim();// 月
			String day = format3.format(date.getTime()).trim();// 日
			String hour = format4.format(date.getTime()).trim();// 小时
			String nf = year.trim() + "\\" + month.trim() + "\\" + day.trim()
					+ "\\" + hour.trim() + "\\";
			nfs = year.trim() + "/" + month.trim() + "/" + day.trim() + "/"
					+ hour.trim();
			path = Config.getImageSave() + Config.getFileImg() + nf + "/";
			File saveDirFile = new File(path);
			if (!saveDirFile.exists()) {
				saveDirFile.mkdirs();
			}
			String filename = UUID.randomUUID().toString() + ".jpg";
			imgStr = imgStr.replace(">", "").replace("<", "");
			String[] data = imgStr.split(" ");  
			FileOutputStream fos = new FileOutputStream(path + filename);
			for(String hexStr : data){  
				byte[] bytes = hexStr2Bytes(hexStr);  
			    fos.write(bytes, 0, bytes.length);    
			    }  
			fos.flush();  
			fos.close();  
			map.put("allurl", Config.getImageAddress() + Config.getFileImg()
					+ nfs + "/" + filename);
			map.put("uploadurl", Config.getFileImg() + nfs + "/" + filename);
			return map;
		} catch (Exception e) {
			logger.info("上传异常" + e.toString()); // 异常信息
			response.setErrorcode(0);
			response.setMessage("获取失败！");

		} finally {
			return null;
		}

	}
	
	 /**
     * 字符串转二进制
     * @param str 要转换的字符串
     * @return  转换后的二进制数组
     */
	public static byte[] hexStr2Bytes(String src){  
        /*对输入值进行规范化整理*/  
        src = src.trim().replace(" ", "").toUpperCase(Locale.US);  
        //处理值初始化  
        int m=0,n=0;  
        int iLen=src.length()/2; //计算长度  
        byte[] ret = new byte[iLen]; //分配存储空间  
          
        for (int i = 0; i < iLen; i++){  
            m=i*2+1;  
            n=m+1;  
            ret[i] = (byte)(Integer.decode("0x"+ src.substring(i*2, m) + src.substring(m,n)) & 0xFF);  
        }  
        return ret;  
    }  

	public Map<String, Object> uploadpic(HttpServletRequest request)
			throws UnsupportedEncodingException {
		try {
			request.setCharacterEncoding("utf-8");
			Map<String, Object> map = new HashMap<String, Object>();
			// 获得磁盘文件条目工厂。
			DiskFileItemFactory factory = new DiskFileItemFactory();
			// 获取文件上传需要保存的路径，upload文件夹需存在。
			String path = "";
			String filename = "";
			String nfs = "";
			String rootDir = request.getServletContext().getRealPath("/");

			logger.info("----------rootDir-------------" + rootDir);
			Calendar date = Calendar.getInstance();
			SimpleDateFormat format1 = new SimpleDateFormat("yyyy ");
			SimpleDateFormat format2 = new SimpleDateFormat("MM ");
			SimpleDateFormat format3 = new SimpleDateFormat("dd ");
			SimpleDateFormat format4 = new SimpleDateFormat("HH ");
			String year = format1.format(date.getTime()).trim();// 年
			String month = format2.format(date.getTime()).trim();// 月
			String day = format3.format(date.getTime()).trim();// 日
			String hour = format4.format(date.getTime()).trim();// 小时

			String nf = year.trim() + "\\" + month.trim() + "\\" + day.trim()
					+ "\\" + hour.trim() + "\\";
			nfs = year.trim() + "/" + month.trim() + "/" + day.trim() + "/"
					+ hour.trim();
			if (rootDir.trim().endsWith(File.separator)) {
				path = rootDir + Config.getFileImg() + nf;

			} else {
				path = rootDir + File.separator + Config.getFileImg() + nf;
			}
			logger.info("------------" + path);

			factory.setRepository(new File(path));
			// 设置缓存的大小，当上传文件的容量超过缓存时，就放到暂时存储室。
			factory.setSizeThreshold(1024 * 1024);
			// 上传处理工具类
			ServletFileUpload upload = new ServletFileUpload(factory);
		 
			logger.info("-----服务器path-------" + path);
			// 调用 parseRequest（request）方法 获得上传文件 FileItem 的集合list 可实现多文件上传。
			List<FileItem> list = (List<FileItem>) upload
					.parseRequest(new ServletRequestContext(request));
			for (FileItem item : list) {
				// 获取表单属性名字。
				String name = item.getFieldName();
				logger.info("-------------name-------------" + name);
				// 获取路径名
				//String value = item.getName();
				// 取到最后一个反斜杠。
				//int start = value.lastIndexOf("\\");
				// 截取上传文件的 字符串名字。+1是去掉反斜杠。
				// String filename = value.substring(start + 1);
				filename = UUID.randomUUID().toString() + ".jpg";
				request.setAttribute(name, filename);
				path = Config.getImageSave() + Config.getFileImg() + nf
						+ "/";
				if (!new File(path).exists()) {
					new File(path).mkdirs();
				}
				logger.info("---------------lastpath---------------"+ path);
				/*
				 * 第三方提供的方法直接写到文件中。 item.write(new File(path,filename));
				 */
				// 收到写到接收的文件中。
				OutputStream out = new FileOutputStream(
						new File(path, filename));

				InputStream in = item.getInputStream();
				int length = 0;
				byte[] buf = new byte[1024];
				System.out.println("获取文件总量的容量:" + item.getSize());
				/*JSONObject s = new JSONObject();
				// 往json对象中加值
				s.put("ReturnCode", 1);// 添加对象
				s.put("ReturnMsg", "succeed");// 添加数组，list和ss都可以
				// s.put("url", Config.getImageAddress() + Config.getZSImg() + "/" + filename);
				s.put("url", Config.getImageSave() + Config.getFileImg()
						+ nfs + "/" + filename);
				// response.getWriter().print(s);*/	
				while ((length = in.read(buf)) != -1) {
					out.write(buf, 0, length);
				}
				in.close();
				out.close();
			}

			map.put("allurl", Config.getImageSave() + Config.getFileImg()
					+ nfs + "/" + filename);
			map.put("uploadurl", Config.getFileImg() + nfs + "/" + filename);
			return map;
		} catch (Exception e) {
			System.out.println(e);
			return null;

		}

	}

	
	/**
	 * 学时上传（写学时）
	 * 
	 * @param request
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@SuppressWarnings("finally")
	@RequestMapping(value = "/updatestuinfo", method = { RequestMethod.GET,
			RequestMethod.POST }, produces = "application/json; charset=utf-8")
	public @ResponseBody String updatestuinfo(HttpServletRequest request)
			throws UnsupportedEncodingException {

		RestResponse response = new RestResponse();
		try {
			String userid = request.getParameter("userid");
		 
			String time = request.getParameter("time");
			String subjectid = request.getParameter("subjectid");
			String videoid = request.getParameter("videoid");
			
			if (userid != null && !userid.isEmpty() && time != null
					&& !time.isEmpty() && subjectid != null && !subjectid.isEmpty()) {
			
					// 添加图片到数据库
					Map<String, Object> paramsMap = new HashMap<String, Object>();
					paramsMap.put("userid", userid);
					paramsMap.put("time", time);
					paramsMap.put("subjectid", subjectid);
					paramsMap.put("videoid", videoid);
				 
					//1、更新tb_StudyStat_query表，增加理论学时和总学时
					bizDao.updateStudyStat_Query(paramsMap);
					//2、判断是否为有效，更新tb_StudyStat_Student
					//从tb_check表中查数据
					List<Map<String, Object>> maps = bizDao.getphotobystuid(paramsMap);	
					if(maps.size() > 0)
					{
						//判断是否大于最大学时，从tb_SubjectParam中查记录
						Map<String, Object> maxtime = bizDao.getSubjectParambysubjectid(Integer.parseInt(subjectid));						
						if(Integer.parseInt(time) > Integer.parseInt(maxtime.get("MaxTime").toString()))
						{
							//部分写有效，部分无效
							paramsMap.put("ValidActualTime", Integer.parseInt(maxtime.get("MaxTime").toString()));
							paramsMap.put("InvalidActualTime", Integer.parseInt(time) - Integer.parseInt(maxtime.get("MaxTime").toString()));
						}else{
							//写有效
							paramsMap.put("ValidActualTime", Integer.parseInt(time));
							paramsMap.put("InvalidActualTime", 0);	
						}
						
					}else{
						paramsMap.put("ValidActualTime", 0);
						paramsMap.put("InvalidActualTime", Integer.parseInt(time));
					}
					//更新tb_StudyStat_Student表
					bizDao.updateStudyStat_Student(paramsMap);
					
					//3、更新tb_StudyStatByDay
					bizDao.updateStudyStatByDay(paramsMap);
					
					//4、判断是否大于大纲学时，写考试结果表
					//查tb_StudyStat_Query
					Map<String, Object> querys = bizDao.getStudyStat_Querybystuid(Integer.parseInt(userid));
					
					//根据学员id获取学驾类型，查tb_Student_Base
					Map<String, Object> schoolsubjet = bizDao.getdrivetypebystuid(Integer.parseInt(userid));
					paramsMap.put("drivetype", schoolsubjet.get("DriveType").toString());
					
					//查tb_SchoolSubjects
					Map<String, Object> SchoolSubject = bizDao.getSchoolSubjectsbysubid(paramsMap);
					int results = 0;
					if(querys != null && SchoolSubject != null)
					{
						//大纲理论学时
						Double schoolsubjectTheory = Double.valueOf(SchoolSubject.get("SyllabusTime_Theoretical").toString());
						//大纲模拟学时
						Double schoolsubjectSimulate = Double.valueOf(SchoolSubject.get("SyllabusTime_Simulate").toString());
						//大纲实操学时
						Double schoolsubjectOperate = Double.valueOf(SchoolSubject.get("SyllabusTime_Operate").toString());
	                    if(subjectid.equals("12"))
	                    {
	                    	//科目1 
	                    	if(Double.valueOf(querys.get("Subject1Theory").toString()) > schoolsubjectTheory)
	                    	{
	                    		//写考试结果表
	                    		results = 1;
	                    	}
	                    	 
	                    }
	                    else if(subjectid.equals("22") )
	                    {
	                    	if(Double.valueOf(querys.get("Subject2Theory").toString()) > schoolsubjectTheory && Double.valueOf(querys.get("Subject2Simulate").toString())>schoolsubjectSimulate && Double.valueOf(querys.get("Subject2Simulate").toString())>schoolsubjectOperate)
	                    	{
	                    		//写考试结果表
	                    		results = 1;
	                    	}
	                    }
	                    else if(subjectid.equals("32"))
	                    {
	                    	if(Double.valueOf(querys.get("Subject3Theory").toString()) > schoolsubjectTheory && Double.valueOf(querys.get("Subject3Simulate").toString())>schoolsubjectSimulate && Double.valueOf(querys.get("Subject3Simulate").toString())>schoolsubjectOperate)
	                    	{
	                    		//写考试结果表
	                    		results = 1;
	                    	}
	                    }
	                    else
	                    {
	                    	if(Double.valueOf(querys.get("Subject4Theory").toString()) > schoolsubjectTheory )
	                    	{
	                    		//写考试结果表
	                    		results = 1;
	                    	}
	                    }
	                    
	                    if(results == 1)
	                    {
	                    	//写考试结果表
	                    	Map<String, Object> examresult = new HashMap<String, Object>();
	                    	examresult.put("studentid", userid);
	                    	examresult.put("MonitorTime", SchoolSubject.get("MonitorTime").toString());
	                    	examresult.put("SyllabusTime", SchoolSubject.get("SyllabusTime").toString());
	                    	examresult.put("StudyTime", time);
	                    	examresult.put("subjectid", subjectid);
	                    	bizDao.InsertStuExamResult(examresult);
	                    	response.setReturnMsg(0, "保存结果表成功");
	                    }
					}
					else
					{
						response.setReturnMsg(1, "汇总表或大纲表无该学员数据");
					}

			} else {
				response.setReturnMsg(1, "用户ID、时间、科目id、学驾类型不能为空...");
				 
			}

		} catch (Exception e) {

			logger.info("写数据异常" + e.toString());
			// 异常信息
			response.setErrorcode(1);
			response.setMessage("获取失败！");

		} finally {
			return response.toJSON();
		}
		
		
	}
	
	 /** 
     * 文件上传 
     * @param request 
     * @param response 
     * @return 
     * @throws ServletException 
     * @throws IOException 
     */ 
	@SuppressWarnings("finally")
    @RequestMapping(value = "/fileUpload", method =
			RequestMethod.POST, produces = "application/json; charset=utf-8")  
    public @ResponseBody String fileUpload(HttpServletRequest request) throws ServletException, IOException{  
    	RestResponse response = new RestResponse();
    	//得到上传文件的保存目录，将上传的文件存放于WEB-INF目录下，不允许外界直接访问，保证上传文件的安全  
        String savePath = "E:/abc";  
        File file = new File(savePath);  
        //判断上传文件的保存目录是否存在  
        if (!file.exists() && !file.isDirectory()) {  
            System.out.println(savePath+"目录不存在，需要创建");  
            //创建目录  
            file.mkdir();  
        }  
        //消息提示  
        String message = "";  
        try{  
            //使用Apache文件上传组件处理文件上传步骤：  
            //1、创建一个DiskFileItemFactory工厂  
            DiskFileItemFactory factory = new DiskFileItemFactory();  
            //2、创建一个文件上传解析器  
            ServletFileUpload upload = new ServletFileUpload(factory);  
            //解决上传文件名的中文乱码  
            upload.setHeaderEncoding("UTF-8");   
            //3、判断提交上来的数据是否是上传表单的数据  
            if(!ServletFileUpload.isMultipartContent(request)){  
                //按照传统方式获取数据  
                System.out.println("没有文件上传");  
            }  
           //4、使用ServletFileUpload解析器解析上传数据，解析结果返回的是一个List<FileItem>集合，每一个FileItem对应一个Form表单的输入项  
           List<FileItem> list = upload.parseRequest((RequestContext) request);  
           for(FileItem item : list){  
               //如果fileitem中封装的是普通输入项的数据  
               if(item.isFormField()){  
                   String name = item.getFieldName();  
                   //解决普通输入项的数据的中文乱码问题  
                  String value = item.getString("UTF-8");  
                  //value = new String(value.getBytes("iso8859-1"),"UTF-8");  
                  System.out.println(name + "=" + value);  
              }else{//如果fileitem中封装的是上传文件  
                   //得到上传的文件名称，  
                   String filename = item.getName();  
                   System.out.println(filename);  
                   if(filename==null || filename.trim().equals("")){  
                       continue;  
                   }  
                  //注意：不同的浏览器提交的文件名是不一样的，有些浏览器提交上来的文件名是带有路径的，如：  c:\a\b\1.txt，而有些只是单纯的文件名，如：1.txt  
                  //处理获取到的上传文件的文件名的路径部分，只保留文件名部分  
                  filename = filename.substring(filename.lastIndexOf("\\")+1);  
                  //获取item中的上传文件的输入流  
                  InputStream in = item.getInputStream();  
                   //创建一个文件输出流  
                   FileOutputStream out = new FileOutputStream(savePath + "\\" + filename);  
                   //创建一个缓冲区  
                   byte buffer[] = new byte[1024];  
                   //判断输入流中的数据是否已经读完的标识  
                  int len = 0;  
                  //循环将输入流读入到缓冲区当中，(len=in.read(buffer))>0就表示in里面还有数据  
                  while((len=in.read(buffer))>0){  
                      //使用FileOutputStream输出流将缓冲区的数据写入到指定的目录(savePath + "\\" + filename)当中  
                      out.write(buffer, 0, len);  
                  }  
                   //关闭输入流  
                   in.close();  
                   //关闭输出流  
                   out.close();  
                  //删除处理文件上传时生成的临时文件  
                  item.delete();  
                  message = "文件上传成功！"; 
                  response.setErrorcode(1);
       		      response.setMessage(message);
              }  
          }  
       }catch (Exception e) {  
    	   message = "文件上传失败！"; 
    	   logger.info("上传异常" + e.toString());
           response.setErrorcode(1);
		   response.setMessage(message);
             
       }finally{
    	   return response.toJSON(); 
       }   
        
    }  
 

}
